package com.guang.springmybatistransaction.service.impl;

import com.guang.springmybatistransaction.dao.UserMapper;
import com.guang.springmybatistransaction.pojo.user.User;
import com.guang.springmybatistransaction.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author lg  参考博客：https://blog.csdn.net/zzhongcy/article/details/102893309
 * @Description
 * @date 2022/9/8 14:19
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Override
    public void doHandlTransaction() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            AtomicReference<Object> transactionStatusSavepoint = null;
            // 这也是一种使用方式！  存在着保存点参考：https://blog.csdn.net/hmmmmm2929/article/details/114984877
            transactionTemplate.execute(transactionStatus -> {
                if (transactionStatus.hasSavepoint()){
                    transactionStatusSavepoint.set(transactionStatus.createSavepoint());
                }
                List<User> users = userMapper.selectAllUser();
                User user = users.get(0);
                user.setEmail("12345678901");
                userMapper.updateByPrimaryKeySelective(user);
                user.setCreatedBy(300);
                userMapper.updateByPrimaryKeySelective(user);
                // 如果存在了一个不满足条件的地方，那么这里应该来执行回滚操作！！！！！！
                try {
                    int i = 1 / 0;
                } catch (Exception e) {
                    Object o = transactionStatusSavepoint.get();
                    transactionStatus.rollbackToSavepoint(o);
                }
                return null;
            });

          /*  transactionTemplate.execute(status -> {

                return null;
            });*/
        } catch (Exception e) {
            System.out.println("出现异常，需要进行回滚");
        }
    }
}
